Explain the First() and FirstOrDefault() functions in LINQ with C#.
Explain First(), FirstOrDefault() function in LINQ with C#.
402
12-Feb-2025
Updated on 12-Feb-2025
Ashutosh Kumar Verma
12-Feb-2025First() vs FirstOrDefault() in LINQ (C#)
Both First() and FirstOrDefault() are used to retrieve the first element from a collection, but they behave differently when no matching element is found.
First()
InvalidOperationException) if no element is found.Example-
find the first even number in the list,
Example (Throws Exception)
FirstOrDefault()
nullfor reference types,0for numeric types) if no element is found.Example-
When to Use What?
Also, Read: LINQ Aggregate functions